import { GetOpenaiChat } from './openai';
import { decryptEvent } from './crypto';
import { SendFeiShuMsg } from './feishu';

type Event = { env: Env; req: Request; ctx: ExecutionContext };

// OPENAI API 接口请求
const OpenaiChatHandler = async (event: Event): Promise<Response> => {
	console.log('openai event:', await event.req.text());
	const jsonData = (await event.req.text()) ? await event.req.json() : '';
	const response = await GetOpenaiChat(event.env, event.req.method, event.req.headers, jsonData);

	const ResHeaders = new Headers(response.headers);
	ResHeaders.set('Access-Control-Allow-Origin', '*');
	return new Response(await response.text(), {
		status: response.status,
		statusText: response.statusText,
		headers: ResHeaders,
	});
};

// 飞书回调函数
const WebhookFeishuEventHandler = async (event: Event): Promise<Response> => {
	// 飞书消息解密
	const feiShuEncrypt = (await (event.req.json() as Promise<{ encrypt: string }>))['encrypt'];
	// console.log('feishu event feiShuEncrypt: ', await event.req.text());

	const decryptFeiShuData = await decryptEvent(event.env.FeiShuEncryptKey, feiShuEncrypt);
	// console.log('feishu event decryptFeiShuData: ', decryptFeiShuData);
	const decryptJsonFeiShuData = JSON.parse(decryptFeiShuData);

	// 异步处理任务，不等待
	if (decryptJsonFeiShuData.event && decryptJsonFeiShuData.event.message) {
		const f = SendFeiShuMsg(event.env, decryptJsonFeiShuData);
		// await f;
		event.ctx.waitUntil(f);
	}

	return new Response(decryptFeiShuData);
};

export { OpenaiChatHandler, WebhookFeishuEventHandler };
